package indi.fritz.bigmap.volme.data;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.util.HashMap;

public class DataEngineLock implements AutoCloseable{
	final static HashMap<Long, FileLock> locks = new HashMap<Long, FileLock>();
	
	FileLock lock;
	Long position = null;
	boolean shared = false;
	
	public DataEngineLock(RandomAccessFile reader, long position,long size,boolean shared) throws IOException {
		this.position = position;
		this.shared = shared;
		if(!shared) {
			while(DataEngineLock.locks.containsKey(position)) {
				FileLock lock = DataEngineLock.locks.get(position);
				if(!lock.channel().isOpen()) {
					synchronized (DataEngineLock.locks) {
						DataEngineLock.locks.remove(position);
					}
				}else {
					try { Thread.sleep(1); } catch (Exception e) { }
				}
			}
			this.lock = reader.getChannel().lock(position, size, shared);
			synchronized (DataEngineLock.locks) { DataEngineLock.locks.put(position, this.lock); }
		}else {
			this.lock = reader.getChannel().lock(position, size, shared);
		}
	}

	@Override
	public void close() throws IOException {
		this.lock.release();
		this.lock.close();
		if(!shared) {
			synchronized (DataEngineLock.locks) {
				DataEngineLock.locks.remove(position);
			}
		}
	}
	
}